package org.example.youdao_translation;

import com.google.gson.Gson;
import okhttp3.*;
import org.example.translation.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.UUID;

public class YoudaoTranslation extends DefaultLangSupportHandler {

    private final MessageDigest sha256;
    private final String APPID = propValueSupplier.get("youdao.appId");
    private final String SECRET = propValueSupplier.get("youdao.secretKey");
    private final OkHttpClient client = new OkHttpClient();
    private final MediaType mediaType = MediaType.parse("application/json");
    private final Gson gson = new Gson();

    public YoudaoTranslation(PropValueSupplier propValueSupplier) {
        super(propValueSupplier);
        translationApiType = TranslationApiType.Interval;
        try {
            sha256 = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public TranslationResponseBean requestTranslation(TranslationPostBean postBean) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        String uuid = UUID.randomUUID().toString();
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        String s1;
        int ql = postBean.getSourceString().length();
        if (postBean.getSourceString().length() > 20){
            s1 = APPID + postBean.getSourceString().substring(0,10) +
                    ql +
                    postBean.getSourceString().substring(ql - 10,ql) +
                    uuid + time + SECRET;
        }else {
            s1 = APPID + postBean.getSourceString() + uuid + time + SECRET;
        }
        sha256.update(s1.getBytes(StandardCharsets.UTF_8));
        String sign = byte2Hex(sha256.digest());
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("q",postBean.getSourceString())
                .add("from",getSupportLang(postBean.getSourceCountry()))
                .add("to",getSupportLang(postBean.getTargetCountry()))
                .add("appKey",APPID)
                .add("salt",uuid)
                .add("sign",sign)
                .add("signType","v3")
                .add("curtime",time);
        Request request = new Request.Builder()
                .header("Content-Type", "application/x-www-form-urlencoded")
                .url("https://openapi.youdao.com/api")
                .post(builder.build())
                .build();
        try {
            Response response = client.newCall(request).execute();
            String s2 = response.body().string();
            YoudaoResponseBean youdaoResponseBean = gson.fromJson(s2, YoudaoResponseBean.class);
            if (youdaoResponseBean != null && youdaoResponseBean.getErrorCode().equals("0")){
                return new TranslationResponseBean()
                        .setTargetResult(youdaoResponseBean.getTranslation().get(0))
                        .setTargetCountry(postBean.getTargetCountry())
                        .setSourceString(postBean.getSourceString())
                        .setSourceCountry(postBean.getSourceCountry());
            }else {
                RuntimeException runtimeException = new RuntimeException("server response:" + s2 +
                        "\nSourceCountry:" + postBean.getSourceCountry() +
                        "\nTargetCountry:" + postBean.getTargetCountry() +
                        "\nContent:" + postBean.getSourceString());
                runtimeException.printStackTrace();
                translation(postBean);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * sha256加密 将byte转为16进制
     *
     * @param bytes 字节码
     * @return 加密后的字符串
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        String temp;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuilder.append("0");
            }
            stringBuilder.append(temp);
        }
        return stringBuilder.toString();
    }

}
